/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "md5chksum.h"
#include <openssl/md5.h>
#include "FileUtils.h"
REGISTER_PLUGIN_CLASS(md5chksum)

bool md5chksum::execute(const string&  actionAsString, cJSON* args, CallbackContext cbc)
{
    if(actionAsString == "file") {
        string path = cJSON_GetArrayItem(args, 0)->valuestring;
        
        path = CFilesystem::getNativeUrl(path);
        FILE *file = fopen(path.c_str(), "rb");
        if(!file) {
            cbc.error("File not found");
            return false;
        }
    
        MD5_CTX md5_context;
        MD5_Init(&md5_context);
    
        const int const_buffer_size = 1024;
        unsigned char data[const_buffer_size];
        size_t bytes_read;
        
        while((bytes_read = fread(data, 1, const_buffer_size, file)) != 0) {
            MD5_Update(&md5_context, data, bytes_read);
        }
    
        unsigned char md5Sum[MD5_DIGEST_LENGTH];
        MD5_Final(md5Sum, &md5_context);
        
        char md5Value[2*MD5_DIGEST_LENGTH+1];
        for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
            sprintf(md5Value+i+i, "%02x", md5Sum[i]); // 以十六进制格式打印每个字节
        }
        fclose(file);
        cbc.success(md5Value);
    }
    return true;
}